#include <rtthread.h>
#include <rtdevice.h>
#include "stm32f1xx_hal.h"
#include <rtdbg.h>
#include "nrf24l01spi.h"

// 在nRF处理的.c文件顶部添加（假设电机代码和nRF代码同工程）：
extern void set_motors_direction(int dir);
extern void set_motors_speed(int spd);
extern void start_motors_pwm(void);
extern void stop_motors_pwm(void);

// 电机引脚定义（若nRF代码未包含）：
#define MOT1_A    22    // 电机1方向A
#define MOT1_B    23    // 电机1方向B
#define MOT1_PWM  21    // 电机1PWM控制
#define MOT2_A    15    // 电机2方向A
#define MOT2_B    12    // 电机2方向B
#define MOT2_PWM  11    // 电机2PWM控制

/* ------------------- LCD（ST7735）硬件引脚定义 ------------------- */
// 软件SPI引脚（与nRF24L01共享部分SPI引脚）
#define LCD_SCK_PIN        GET_PIN(A, 5)    // 与nRF24L01共享SCK
#define LCD_SDA_PIN        GET_PIN(A, 7)    // 与nRF24L01共享MOSI
// LCD控制引脚（独立）
#define LCD_CS_PIN         GET_PIN(A, 4)    // LCD片选，低电平有效
#define LCD_RES_PIN        GET_PIN(A, 8)    // LCD复位
#define LCD_DC_PIN         GET_PIN(B, 15)   // LCD数据/命令
#define LCD_BLK_PIN        GET_PIN(B, 14)   // LCD背光

/* ------------------- 高速GPIO寄存器操作 ------------------- */
#define GPIOA_BSRR         GPIOA->BSRR
#define GPIOB_BSRR         GPIOB->BSRR
#define GPIOA_IDR          GPIOA->IDR

/* ------------------- LCD引脚操作宏 ------------------- */
#define LCD_CS_HIGH        (GPIOA_BSRR = (1 << (LCD_CS_PIN & 0x0F)))
#define LCD_CS_LOW         (GPIOA_BSRR = (1 << (LCD_CS_PIN & 0x0F)) << 16)
#define LCD_SCK_HIGH       (GPIOA_BSRR = (1 << (LCD_SCK_PIN & 0x0F)))
#define LCD_SCK_LOW        (GPIOA_BSRR = (1 << (LCD_SCK_PIN & 0x0F)) << 16)
#define LCD_SDA_HIGH       (GPIOA_BSRR = (1 << (LCD_SDA_PIN & 0x0F)))
#define LCD_SDA_LOW        (GPIOA_BSRR = (1 << (LCD_SDA_PIN & 0x0F)) << 16)
#define LCD_RES_HIGH       (GPIOA_BSRR = (1 << (LCD_RES_PIN & 0x0F)))
#define LCD_RES_LOW        (GPIOA_BSRR = (1 << (LCD_RES_PIN & 0x0F)) << 16)
#define LCD_DC_HIGH        (GPIOB_BSRR = (1 << (LCD_DC_PIN & 0x0F)))
#define LCD_DC_LOW         (GPIOB_BSRR = (1 << (LCD_DC_PIN & 0x0F)) << 16)
#define LCD_BLK_HIGH       (GPIOB_BSRR = (1 << (LCD_BLK_PIN & 0x0F)))
#define LCD_BLK_LOW        (GPIOB_BSRR = (1 << (LCD_BLK_PIN & 0x0F)) << 16)

/* ------------------- nRF24L01引脚操作宏 ------------------- */
#define NRF_CS_HIGH        rt_pin_write(NRF24L01_CS_PIN, PIN_HIGH)
#define NRF_CS_LOW         rt_pin_write(NRF24L01_CS_PIN, PIN_LOW)
#define NRF_CE_HIGH        rt_pin_write(NRF24L01_CE_PIN, PIN_HIGH)
#define NRF_CE_LOW         rt_pin_write(NRF24L01_CE_PIN, PIN_LOW)
#define NRF_SCK_HIGH       rt_pin_write(NRF24L01_SCK_PIN, PIN_HIGH)
#define NRF_SCK_LOW        rt_pin_write(NRF24L01_SCK_PIN, PIN_LOW)
#define NRF_MOSI_HIGH      rt_pin_write(NRF24L01_MOSI_PIN, PIN_HIGH)
#define NRF_MOSI_LOW       rt_pin_write(NRF24L01_MOSI_PIN, PIN_LOW)
#define NRF_MISO_READ      rt_pin_read(NRF24L01_MISO_PIN)

/* ------------------- LCD ST7735核心命令定义 ------------------- */
#define CMD_SOFT_RESET     0x01  // 软件复位
#define CMD_SLEEP_OUT      0x11  // 退出睡眠模式
#define CMD_COLOR_MODE     0x3A  // 颜色模式配置
#define CMD_MADCTL         0x36  // 显示方向配置
#define CMD_CASET          0x2A  // 列地址范围设置
#define CMD_RASET          0x2B  // 行地址范围设置
#define CMD_RAM_WR         0x2C  // 写入GRAM
#define CMD_DISPLAY_ON     0x29  // 开启显示
#define CMD_READ_ID        0x04  // 读取LCD ID（3字节）

/* ------------------- LCD RGB565颜色定义 ------------------- */
#define COLOR_BLACK        0x0000  // 黑色（背景默认）
#define COLOR_WHITE        0xFFFF  // 白色（文字默认）
#define COLOR_BLUE         0x001F  // 蓝色
#define COLOR_RED          0xF800  // 红色
#define COLOR_GREEN        0x07E0  // 绿色
#define COLOR_YELLOW       0xFFE0  // 黄色（标题用）
#define COLOR_CYAN         0x07FF  // 青色（数据用）
#define COLOR_MAGENTA      0xF81F  // 品红（错误提示）

// 全局接收缓冲区（中断安全）
static uint8_t g_rx_buffer[PAYLOAD_WIDTH] = {0};
// 数据就绪标志（中断置位，主线程清零）
static volatile rt_bool_t g_rx_data_ready = RT_FALSE;

/* ------------------- 软件SPI核心函数（LCD专用） ------------------- */
static void lcd_spi_send_bit(uint8_t bit) {
    // 确保nRF24L01未被选中
    NRF_CS_HIGH;

    LCD_SCK_LOW;
    rt_hw_us_delay(2);

    bit ? LCD_SDA_HIGH : LCD_SDA_LOW;
    rt_hw_us_delay(2);

    LCD_SCK_HIGH;
    rt_hw_us_delay(2);

    LCD_SCK_LOW;
}

static void lcd_spi_send_byte(uint8_t tx_data) {
    // 确保nRF24L01未被选中
    NRF_CS_HIGH;

    for (int i = 0; i < 8; i++) {
        lcd_spi_send_bit((tx_data & 0x80) ? 1 : 0);
        tx_data <<= 1;
    }
}

/* ------------------- LCD ST7735驱动核心函数 ------------------- */
static void lcd_reset(void) {
    LCD_RES_LOW;
    rt_thread_mdelay(10);
    LCD_RES_HIGH;
    rt_thread_mdelay(5);
}

static void lcd_send_cmd(uint8_t cmd) {
    LCD_CS_LOW;
    LCD_DC_LOW;
    lcd_spi_send_byte(cmd);
    LCD_CS_HIGH;
}

static void lcd_send_data(uint8_t data) {
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(data);
    LCD_CS_HIGH;
}

static void lcd_send_data_burst(const uint8_t *data, uint32_t len) {
    if (data == RT_NULL || len == 0) return;

    LCD_CS_LOW;
    LCD_DC_HIGH;
    for (uint32_t i = 0; i < len; i++) {
        lcd_spi_send_byte(data[i]);
    }
    LCD_CS_HIGH;
}

static void lcd_init(void) {
    // 初始化LCD引脚
    rt_pin_mode(LCD_CS_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LCD_SCK_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LCD_SDA_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LCD_RES_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LCD_DC_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LCD_BLK_PIN, PIN_MODE_OUTPUT);

    // 初始电平
    LCD_CS_HIGH;
    LCD_SCK_LOW;
    LCD_SDA_LOW;
    LCD_RES_HIGH;
    LCD_DC_LOW;
    LCD_BLK_LOW;

    // 复位LCD
    lcd_reset();

    // 软件复位
    lcd_send_cmd(CMD_SOFT_RESET);
    rt_thread_mdelay(5);

    // 退出睡眠模式
    lcd_send_cmd(CMD_SLEEP_OUT);
    rt_thread_mdelay(5);

    // 设置颜色模式：RGB565
    lcd_send_cmd(CMD_COLOR_MODE);
    lcd_send_data(0x05);
    rt_thread_mdelay(1);

    // 设置显示方向
    lcd_send_cmd(CMD_MADCTL);
    lcd_send_data(0x00);
    rt_thread_mdelay(1);

    // 设置列地址范围（128列：0~127）
    lcd_send_cmd(CMD_CASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x00);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x7F);
    LCD_CS_HIGH;
    rt_thread_mdelay(1);

    // 设置行地址范围（128行：0~127）
    lcd_send_cmd(CMD_RASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x00);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x7F);
    LCD_CS_HIGH;
    rt_thread_mdelay(1);

    // 开启显示
    lcd_send_cmd(CMD_DISPLAY_ON);
    rt_thread_mdelay(5);

    // 开启背光
    LCD_BLK_HIGH;
    LOG_I("LCD ST7735 init success (128x128)");
}

static void lcd_fill_screen(uint16_t color) {
    uint8_t color_buf[2] = {color >> 8, color & 0xFF};
    const uint32_t TOTAL_PIXEL = 128 * 128;

    lcd_send_cmd(CMD_CASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x00);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x7F);
    LCD_CS_HIGH;

    lcd_send_cmd(CMD_RASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x00);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(0x7F);
    LCD_CS_HIGH;

    lcd_send_cmd(CMD_RAM_WR);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    for (uint32_t i = 0; i < TOTAL_PIXEL; i++) {
        lcd_spi_send_byte(color_buf[0]);
        lcd_spi_send_byte(color_buf[1]);
    }
    LCD_CS_HIGH;
}

static void lcd_draw_pixel(uint8_t x, uint8_t y, uint16_t color) {
    if (x > 127 || y > 127) return;

    lcd_send_cmd(CMD_CASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(x);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(x);
    LCD_CS_HIGH;

    lcd_send_cmd(CMD_RASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(y);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(y);
    LCD_CS_HIGH;

    lcd_send_cmd(CMD_RAM_WR);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(color >> 8);
    lcd_spi_send_byte(color & 0xFF);
    LCD_CS_HIGH;
}

/* ------------------- 5×8 ASCII字模库 ------------------- */
const uint8_t ascii_font[96][5] = {
    {0x00, 0x00, 0x00, 0x00, 0x00}, // 0x20 (空格)
    {0x00, 0x00, 0x5F, 0x00, 0x00}, // 0x21 (!)
    {0x00, 0x07, 0x00, 0x07, 0x00}, // 0x22 (")
    {0x14, 0x7F, 0x14, 0x7F, 0x14}, // 0x23 (#)
    {0x24, 0x2A, 0x7F, 0x2A, 0x12}, // 0x24 ($)
    {0x23, 0x13, 0x08, 0x64, 0x62}, // 0x25 (%)
    {0x36, 0x49, 0x55, 0x22, 0x50}, // 0x26 (&)
    {0x00, 0x05, 0x03, 0x00, 0x00}, // 0x27 (')
    {0x00, 0x1C, 0x22, 0x41, 0x00}, // 0x28 (()
    {0x00, 0x41, 0x22, 0x1C, 0x00}, // 0x29 ())
    {0x14, 0x08, 0x3E, 0x08, 0x14}, // 0x2A (*)
    {0x08, 0x08, 0x3E, 0x08, 0x08}, // 0x2B (+)
    {0x00, 0x50, 0x30, 0x00, 0x00}, // 0x2C (,)
    {0x08, 0x08, 0x08, 0x08, 0x08}, // 0x2D (-)
    {0x00, 0x60, 0x60, 0x00, 0x00}, // 0x2E (.)
    {0x20, 0x10, 0x08, 0x04, 0x02}, // 0x2F (/)
    {0x3E, 0x51, 0x49, 0x45, 0x3E}, // 0x30 (0)
    {0x00, 0x42, 0x7F, 0x40, 0x00}, // 0x31 (1)
    {0x42, 0x61, 0x51, 0x49, 0x46}, // 0x32 (2)
    {0x21, 0x41, 0x45, 0x4B, 0x31}, // 0x33 (3)
    {0x18, 0x14, 0x12, 0x7F, 0x10}, // 0x34 (4)
    {0x27, 0x45, 0x45, 0x45, 0x39}, // 0x35 (5)
    {0x3C, 0x4A, 0x49, 0x49, 0x30}, // 0x36 (6)
    {0x01, 0x71, 0x09, 0x05, 0x03}, // 0x37 (7)
    {0x36, 0x49, 0x49, 0x49, 0x36}, // 0x38 (8)
    {0x06, 0x49, 0x49, 0x29, 0x1E}, // 0x39 (9)
    {0x00, 0x36, 0x36, 0x00, 0x00}, // 0x3A (:)
    {0x00, 0x56, 0x36, 0x00, 0x00}, // 0x3B (;)
    {0x00, 0x08, 0x14, 0x22, 0x41}, // 0x3C (<)
    {0x14, 0x14, 0x14, 0x14, 0x14}, // 0x3D (=)
    {0x00, 0x41, 0x22, 0x14, 0x08}, // 0x3E (>)
    {0x02, 0x01, 0x51, 0x09, 0x06}, // 0x3F (?)
    {0x32, 0x49, 0x79, 0x41, 0x3E}, // 0x40 (@)
    {0x7C, 0x12, 0x11, 0x12, 0x7C}, // 0x41 (A)
    {0x7F, 0x49, 0x49, 0x49, 0x36}, // 0x42 (B)
    {0x3E, 0x41, 0x41, 0x41, 0x22}, // 0x43 (C)
    {0x7F, 0x41, 0x41, 0x22, 0x1C}, // 0x44 (D)
    {0x7F, 0x49, 0x49, 0x49, 0x41}, // 0x45 (E)
    {0x7F, 0x09, 0x09, 0x09, 0x01}, // 0x46 (F)
    {0x3E, 0x41, 0x49, 0x49, 0x3A}, // 0x47 (G)
    {0x7F, 0x08, 0x08, 0x08, 0x7F}, // 0x48 (H)
    {0x00, 0x41, 0x7F, 0x41, 0x00}, // 0x49 (I)
    {0x20, 0x40, 0x41, 0x3F, 0x01}, // 0x4A (J)
    {0x7F, 0x08, 0x14, 0x22, 0x41}, // 0x4B (K)
    {0x7F, 0x40, 0x40, 0x40, 0x40}, // 0x4C (L)
    {0x7F, 0x02, 0x0C, 0x02, 0x7F}, // 0x4D (M)
    {0x7F, 0x04, 0x08, 0x10, 0x7F}, // 0x4E (N)
    {0x3E, 0x41, 0x41, 0x41, 0x3E}, // 0x4F (O)
    {0x7F, 0x09, 0x09, 0x09, 0x06}, // 0x50 (P)
    {0x3E, 0x41, 0x51, 0x21, 0x5E}, // 0x51 (Q)
    {0x7F, 0x09, 0x19, 0x29, 0x46}, // 0x52 (R)
    {0x46, 0x49, 0x49, 0x49, 0x31}, // 0x53 (S)
    {0x01, 0x01, 0x7F, 0x01, 0x01}, // 0x54 (T)
    {0x3F, 0x40, 0x40, 0x40, 0x3F}, // 0x55 (U)
    {0x1F, 0x20, 0x40, 0x20, 0x1F}, // 0x56 (V)
    {0x3F, 0x40, 0x38, 0x40, 0x3F}, // 0x57 (W)
    {0x63, 0x14, 0x08, 0x14, 0x63}, // 0x58 (X)
    {0x07, 0x08, 0x70, 0x08, 0x07}, // 0x59 (Y)
    {0x61, 0x51, 0x49, 0x45, 0x43}, // 0x5A (Z)
    {0x00, 0x7F, 0x41, 0x41, 0x00}, // 0x5B ([)
    {0x02, 0x04, 0x08, 0x10, 0x20}, // 0x5C (\)
    {0x00, 0x41, 0x41, 0x7F, 0x00}, // 0x5D (])
    {0x04, 0x02, 0x01, 0x02, 0x04}, // 0x5E (^)
    {0x40, 0x40, 0x40, 0x40, 0x40}, // 0x5F (_)
    {0x00, 0x01, 0x02, 0x04, 0x00}, // 0x60 (`)
    {0x20, 0x54, 0x54, 0x54, 0x78}, // 0x61 (a)
    {0x7F, 0x48, 0x44, 0x44, 0x38}, // 0x62 (b)
    {0x38, 0x44, 0x44, 0x44, 0x20}, // 0x63 (c)
    {0x38, 0x44, 0x44, 0x48, 0x7F}, // 0x64 (d)
    {0x38, 0x54, 0x54, 0x54, 0x18}, // 0x65 (e)
    {0x08, 0x7E, 0x09, 0x01, 0x02}, // 0x66 (f)
    {0x0C, 0x52, 0x52, 0x52, 0x3E}, // 0x67 (g)
    {0x7F, 0x08, 0x04, 0x04, 0x78}, // 0x68 (h)
    {0x00, 0x44, 0x7D, 0x40, 0x00}, // 0x69 (i)
    {0x20, 0x40, 0x44, 0x3D, 0x00}, // 0x6A (j)
    {0x7F, 0x10, 0x28, 0x44, 0x00}, // 0x6B (k)
    {0x00, 0x41, 0x7F, 0x40, 0x00}, // 0x6C (l)
    {0x7C, 0x04, 0x18, 0x04, 0x78}, // 0x6D (m)
    {0x7C, 0x08, 0x04, 0x04, 0x78}, // 0x6E (n)
    {0x38, 0x44, 0x44, 0x44, 0x38}, // 0x6F (o)
    {0x7C, 0x14, 0x14, 0x14, 0x08}, // 0x70 (p)
    {0x08, 0x14, 0x14, 0x18, 0x7C}, // 0x71 (q)
    {0x7C, 0x08, 0x04, 0x04, 0x08}, // 0x72 (r)
    {0x08, 0x54, 0x54, 0x54, 0x20}, // 0x73 (s)
    {0x04, 0x3F, 0x44, 0x40, 0x20}, // 0x74 (t)
    {0x3C, 0x40, 0x40, 0x20, 0x7C}, // 0x75 (u)
    {0x1C, 0x20, 0x40, 0x20, 0x1C}, // 0x76 (v)
    {0x3C, 0x40, 0x30, 0x40, 0x3C}, // 0x77 (w)
    {0x44, 0x28, 0x10, 0x28, 0x44}, // 0x78 (x)
    {0x0C, 0x50, 0x50, 0x50, 0x3C}, // 0x79 (y)
    {0x44, 0x64, 0x54, 0x4C, 0x44}, // 0x7A (z)
    {0x00, 0x08, 0x36, 0x41, 0x00}, // 0x7B ({)
    {0x00, 0x00, 0x7F, 0x00, 0x00}, // 0x7C (|)
    {0x00, 0x41, 0x36, 0x08, 0x00}, // 0x7D (})
    {0x10, 0x08, 0x08, 0x10, 0x08}, // 0x7E (~)
};

static void lcd_draw_char(uint8_t x, uint8_t y, char c, uint16_t color) {
    uint8_t idx = c - 0x20;
    if (idx >= 96) idx = 0;

    const uint8_t *font = ascii_font[idx];
    for (int col = 0; col < 5; col++) {
        for (int row = 0; row < 8; row++) {
            if (font[col] & (1 << row)) {
                lcd_draw_pixel(x + col, y + row, color);
            }
        }
    }
}

static void lcd_draw_string(uint8_t x, uint8_t y, const char *str, uint16_t color) {
    if (str == RT_NULL) return;

    uint8_t curr_x = x;
    while (*str != '\0') {
        if (curr_x > 127 - 5 || y > 127 - 8) break;

        lcd_draw_char(curr_x, y, *str, color);
        curr_x += 7;
        str++;
    }
}

static void lcd_clear_area(uint8_t x1, uint8_t x2, uint8_t y1, uint8_t y2, uint16_t bg_color) {
    if (x1 > x2 || y1 > y2) return;

    uint8_t color_h = bg_color >> 8;
    uint8_t color_l = bg_color & 0xFF;
    uint32_t pixel_cnt = (x2 - x1 + 1) * (y2 - y1 + 1);

    lcd_send_cmd(CMD_CASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(x1);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(x2);
    LCD_CS_HIGH;

    lcd_send_cmd(CMD_RASET);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(y1);
    lcd_spi_send_byte(0x00); lcd_spi_send_byte(y2);
    LCD_CS_HIGH;

    lcd_send_cmd(CMD_RAM_WR);
    LCD_CS_LOW;
    LCD_DC_HIGH;
    for (uint32_t i = 0; i < pixel_cnt; i++) {
        lcd_spi_send_byte(color_h);
        lcd_spi_send_byte(color_l);
    }
    LCD_CS_HIGH;
}

/* ------------------- nRF24L01 软件SPI通信函数 ------------------- */
static uint8_t nrf_spi_transfer(uint8_t tx_data) {
    uint8_t rx_data = 0;

    // 确保LCD未被选中
    LCD_CS_HIGH;

    for (uint8_t bit = 0; bit < 8; bit++) {
        // 输出MOSI bit（高位先传）
        if ((tx_data >> (7 - bit)) & 0x01) {
            NRF_MOSI_HIGH;
        } else {
            NRF_MOSI_LOW;
        }
        rt_hw_us_delay(5);

        // SCK上升沿：读取MISO
        NRF_SCK_HIGH;
        rt_hw_us_delay(5);

        rx_data |= (NRF_MISO_READ << (7 - bit));

        // SCK下降沿
        NRF_SCK_LOW;
        rt_hw_us_delay(5);
    }
    return rx_data;
}

static uint8_t nrf_read_reg(uint8_t reg) {
    uint8_t cmd = NRF24L01_CMD_R_REGISTER | (reg & 0x1F);
    uint8_t val;

    NRF_CS_LOW;
    rt_hw_us_delay(10);

    nrf_spi_transfer(cmd);
    val = nrf_spi_transfer(0xFF);

    NRF_CS_HIGH;
    rt_hw_us_delay(10);

    return val;
}

static void nrf_write_reg(uint8_t reg, uint8_t value) {
    uint8_t cmd = NRF24L01_CMD_W_REGISTER | (reg & 0x1F);

    NRF_CS_LOW;
    rt_hw_us_delay(10);

    nrf_spi_transfer(cmd);
    nrf_spi_transfer(value);

    NRF_CS_HIGH;
    rt_hw_us_delay(10);
}

static void nrf_write_buf(uint8_t reg, const uint8_t *buf, uint8_t len) {
    uint8_t cmd = NRF24L01_CMD_W_REGISTER | (reg & 0x1F);

    NRF_CS_LOW;
    rt_hw_us_delay(10);

    nrf_spi_transfer(cmd);
    for (uint8_t i = 0; i < len; i++) {
        nrf_spi_transfer(buf[i]);
    }

    NRF_CS_HIGH;
    rt_hw_us_delay(10);
}

static void nrf_read_buf(uint8_t reg, uint8_t *buf, uint8_t len) {
    uint8_t cmd = NRF24L01_CMD_R_REGISTER | (reg & 0x1F);

    NRF_CS_LOW;
    rt_hw_us_delay(10);

    nrf_spi_transfer(cmd);
    for (uint8_t i = 0; i < len; i++) {
        buf[i] = nrf_spi_transfer(0xFF);
    }

    NRF_CS_HIGH;
    rt_hw_us_delay(10);
}

static void nrf_flush_tx(void) {
    NRF_CS_LOW;
    rt_hw_us_delay(10);

    nrf_spi_transfer(NRF24L01_CMD_FLUSH_TX);

    NRF_CS_HIGH;
    rt_hw_us_delay(10);
}

static void nrf_flush_rx(void) {
    NRF_CS_LOW;
    rt_hw_us_delay(10);

    nrf_spi_transfer(NRF24L01_CMD_FLUSH_RX);

    NRF_CS_HIGH;
    rt_hw_us_delay(10);
}

rt_err_t nrf24l01_init(void) {
    uint8_t check;

    // 1. 初始化所有引脚（含IRQ）
    rt_pin_mode(NRF24L01_CS_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(NRF24L01_CE_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(NRF24L01_SCK_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(NRF24L01_MOSI_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(NRF24L01_MISO_PIN, PIN_MODE_INPUT);
    rt_pin_mode(NRF24L01_IRQ_PIN, PIN_MODE_INPUT_PULLUP);  // IRQ上拉输入（防干扰）

    // 初始电平
    NRF_CS_HIGH;
    NRF_CE_LOW;
    NRF_SCK_LOW;
    NRF_MOSI_LOW;
    rt_hw_us_delay(10);

    // 2. 检查nRF24L01连接（可选，注释则跳过检查）
    check = nrf_read_reg(NRF24L01_REG_CONFIG);
    LOG_D("nRF CONFIG init value: 0x%02X", check);
    // if (check != 0x08) { LOG_E("nRF not found!"); return -RT_ERROR; }

    // 3. 基础寄存器配置（与发送端一致）
    NRF_CE_LOW;  // 配置前拉低CE
    nrf_write_reg(NRF24L01_REG_EN_AA, 0x01);        // 管道0自动应答使能
    nrf_write_reg(NRF24L01_REG_EN_RXADDR, 0x01);    // 管道0接收使能
    nrf_write_reg(NRF24L01_REG_SETUP_AW, 0x03);     // 地址宽度5字节
    nrf_write_reg(NRF24L01_REG_SETUP_RETR, 0x1A);   // 500us重发延迟，10次重试
    nrf_write_reg(NRF24L01_REG_RF_CH, RF_CHANNEL);  // 射频通道
    nrf_write_reg(NRF24L01_REG_RF_SETUP, 0x0F);     // 0dBm功率，2Mbps速率
    nrf_write_reg(NRF24L01_REG_RX_PW_P0, PAYLOAD_WIDTH); // 管道0数据长度
    nrf_write_buf(NRF24L01_REG_RX_ADDR_P0, DEVICE_ADDR, 5); // 接收地址
    nrf_write_buf(NRF24L01_REG_TX_ADDR, DEVICE_ADDR, 5);   // 发送地址（ACK用）
    nrf_write_reg(NRF24L01_REG_FEATURE, 0x06);      // 使能动态负载+ACK负载
    nrf_write_reg(NRF24L01_REG_DYNPD, 0x01);        // 管道0开启动态负载

    // 4. 清除中断标志（TX_DS/MAX_RT/RX_DR）
    nrf_write_reg(NRF24L01_REG_STATUS, 0x70);

    // 5. 注册IRQ中断回调（下降沿触发）
    rt_err_t irq_ret = rt_pin_attach_irq(
        NRF24L01_IRQ_PIN,          // IRQ引脚
        PIN_IRQ_MODE_FALLING,      // 下降沿触发
        nrf24l01_irq_callback,     // 回调函数
        RT_NULL                    // 回调参数
    );
    if (irq_ret != RT_EOK) {
        LOG_E("IRQ callback attach failed!");
        return irq_ret;
    }
    rt_pin_irq_enable(NRF24L01_IRQ_PIN, PIN_IRQ_ENABLE);  // 使能中断

    // 6. 初始化为接收模式
    nrf24l01_set_rx_mode();

    LOG_I("nRF24L01 init OK (IRQ enabled)");
    return RT_EOK;
}

void nrf24l01_set_tx_mode(void) {
    NRF_CE_LOW;
    // 配置为发送模式，上电
    nrf_write_reg(NRF24L01_REG_CONFIG, 0x0E);
    rt_thread_mdelay(1);
    NRF_CE_HIGH;
    rt_thread_mdelay(1);
}

void nrf24l01_set_rx_mode(void) {
    uint8_t config;
    LOG_I("Enter RX mode");

    // 1. 清空RX FIFO（避免残留数据）
    NRF_CS_LOW;
    rt_hw_us_delay(10);
    nrf_spi_transfer(NRF24L01_CMD_FLUSH_RX);
    NRF_CS_HIGH;
    rt_hw_us_delay(10);

    // 2. 配置接收模式：PRIM_RX=1（接收），PWR_UP=1（上电），CRC使能
    config = nrf_read_reg(NRF24L01_REG_CONFIG);
    LOG_D("CONFIG before RX: 0x%02X", config);
    config = (config & 0xF9) | 0x03;  // 0xF9清除PRIM_RX/PWR_UP，0x03置1
    nrf_write_reg(NRF24L01_REG_CONFIG, config);

    // 3. 确认关键寄存器（防止配置丢失）
    nrf_write_reg(NRF24L01_REG_EN_AA, 0x01);
    nrf_write_reg(NRF24L01_REG_RX_PW_P0, PAYLOAD_WIDTH);

    // 4. 使能接收（CE置高，等待PLL稳定， datasheet要求≥130us）
    NRF_CE_HIGH;
    rt_thread_mdelay(1);  // 1ms足够稳定
    LOG_I("RX mode ready (wait IRQ)");
}
rt_err_t nrf24l01_send_data(uint8_t *payload, uint8_t len) {
    if (len > PAYLOAD_WIDTH) len = PAYLOAD_WIDTH;

    NRF_CE_LOW;

    // 清除发送FIFO
    nrf_flush_tx();

    // 写入发送数据
    NRF_CS_LOW;
    rt_hw_us_delay(10);
    nrf_spi_transfer(NRF24L01_CMD_W_TX_PAYLOAD);
    for (uint8_t i = 0; i < len; i++) {
        nrf_spi_transfer(payload[i]);
    }
    NRF_CS_HIGH;
    rt_hw_us_delay(10);

    // 启动发送
    NRF_CE_HIGH;
    rt_hw_us_delay(15);  // 至少10us
    NRF_CE_LOW;

    // 等待发送完成或超时
    rt_tick_t start_tick = rt_tick_get();
    while (1) {
        uint8_t status = nrf_read_reg(NRF24L01_REG_STATUS);

        // 发送成功
        if (status & (1 << 5)) {
            nrf_write_reg(NRF24L01_REG_STATUS, 1 << 5);  // 清除TX_DS标志
            return RT_EOK;
        }

        // 发送失败（超过重发次数）
        if (status & (1 << 4)) {
            nrf_write_reg(NRF24L01_REG_STATUS, 1 << 4);  // 清除MAX_RT标志
            nrf_flush_tx();  // 清除发送FIFO
            return -RT_ERROR;
        }

        // 超时检查（100ms）
        if (rt_tick_get() - start_tick > rt_tick_from_millisecond(100)) {
            return -RT_ETIMEOUT;
        }

        rt_thread_mdelay(1);
    }
}

rt_err_t nrf24l01_receive_data(uint8_t *buffer, uint8_t len) {
    if (buffer == RT_NULL || len < PAYLOAD_WIDTH) {
        return -RT_ERROR;
    }

    // 读取接收数据
    NRF_CS_LOW;
    rt_hw_us_delay(10);
    nrf_spi_transfer(NRF24L01_CMD_R_RX_PAYLOAD);
    for (uint8_t i = 0; i < PAYLOAD_WIDTH; i++) {
        buffer[i] = nrf_spi_transfer(0xFF);
    }
    NRF_CS_HIGH;
    rt_hw_us_delay(10);

    // 清除接收标志
    nrf_write_reg(NRF24L01_REG_STATUS, 1 << 6);

    // 清除接收FIFO
    nrf_flush_rx();

    return RT_EOK;
}

rt_bool_t nrf24l01_data_available(void) {
    return (nrf_read_reg(NRF24L01_REG_STATUS) & (1 << 6)) ? RT_TRUE : RT_FALSE;
}

static void nrf_lcd_test_thread(void *param) {
    char str[32];
    uint8_t config, status, rf_ch;
    static uint16_t rx_count = 0;  // 接收计数

    rt_pin_mode(MOT1_A, PIN_MODE_OUTPUT);
       rt_pin_mode(MOT1_B, PIN_MODE_OUTPUT);
       rt_pin_mode(MOT2_A, PIN_MODE_OUTPUT);
       rt_pin_mode(MOT2_B, PIN_MODE_OUTPUT);

    // 1. 初始化LCD并显示标题
    lcd_init();
    lcd_fill_screen(COLOR_BLACK);
    lcd_draw_string(10, 5, "nRF24L01 IRQ Test", COLOR_YELLOW);
    lcd_draw_string(10, 20, "Mode: RX (IRQ)", COLOR_GREEN);

    // 2. 初始化nRF24L01（含IRQ）
    if (nrf24l01_init() != RT_EOK) {
        lcd_draw_string(10, 35, "nRF Init Fail", COLOR_RED);
        while (1) rt_thread_mdelay(1000);
    }
    lcd_draw_string(10, 35, "nRF Init OK", COLOR_GREEN);

    // 3. 显示nRF配置信息
    config = nrf_read_reg(NRF24L01_REG_CONFIG);
    status = nrf_read_reg(NRF24L01_REG_STATUS);
    rf_ch = nrf_read_reg(NRF24L01_REG_RF_CH);
    rt_sprintf(str, "CONFIG: 0x%02X", config);
    lcd_draw_string(10, 50, str, COLOR_CYAN);
    rt_sprintf(str, "STATUS: 0x%02X", status);
    lcd_draw_string(10, 60, str, COLOR_CYAN);
    rt_sprintf(str, "RF_CH: 0x%02X", rf_ch);
    lcd_draw_string(10, 70, str, COLOR_CYAN);

    // 4. 显示接收提示
    lcd_draw_string(10, 85, "Wait RX Data...", COLOR_YELLOW);
    lcd_draw_string(10, 100, "RX: ---- ---- ----", COLOR_WHITE);
    lcd_draw_string(10, 118, "RX Count: 0", COLOR_CYAN);
    rt_pin_mode(GET_PIN(C, 13), PIN_MODE_OUTPUT);
    rt_pin_write(GET_PIN(C, 13), PIN_HIGH); // 初始状态：灭
    // 5. 主循环：轮询数据标志，更新LCD
    while (1) {
        if (g_rx_data_ready) {
            g_rx_data_ready = RT_FALSE;

            if (PAYLOAD_WIDTH == 2) {
                // 匹配停止指令: 0xF2 0xF1
                if (g_rx_buffer[0] == CMD_STOP[0] && g_rx_buffer[1] == CMD_STOP[1]) {
                    stop_motors_pwm(); // 停止电机PWM
                    rt_kprintf("st\r\n");
                }
                // 匹配前进指令: 0xF2 0xF2
                else if (g_rx_buffer[0] == CMD_FORWARD[0] && g_rx_buffer[1] == CMD_FORWARD[1]) {
                    //set_motors_direction(1); // 正转（方向1）
                    motor_forward(5);
                }
                // 匹配前进指令: 0xF2 0xF4
                 else if (g_rx_buffer[0] == car_y[0] && g_rx_buffer[1] == car_y[1]) {
                     motor_turn_right(1,3);

                 }
                // 匹配前进指令: 0xF2 0xF5
                 else if (g_rx_buffer[0] == car_z[0] && g_rx_buffer[1] == car_z[1]) {
                     motor_turn_left(1,3);
                 }
                // 匹配前进指令: 0xF2 0xF3
                  else if (g_rx_buffer[0] == car_t[0] && g_rx_buffer[1] == car_t[1]) {
                      motor_back(3);
                  }
                // 未知指令
                else {
                    rt_kprintf("Unknown command: 0x%02X 0x%02X", g_rx_buffer[0], g_rx_buffer[1]);
                }
            } else {
                rt_kprintf("Payload length error! Expected 2 bytes, got %d", PAYLOAD_WIDTH);
            }

            // （可选）更新LCD显示指令   由于此处与上面的spi隔离的不是很好 就是如果接收的时候 irn触发中断了 但是还在刷新屏幕 就产生了死机
            /*
            char cmd_str[32];
            rt_sprintf(cmd_str, "CMD: %02X %02X", g_rx_buffer[0], g_rx_buffer[1]);
            lcd_clear_area(10, 120, 100, 115, COLOR_BLACK);
            lcd_draw_string(10, 100, cmd_str, COLOR_WHITE);*/
        }

        rt_thread_mdelay(100); // 降低CPU占用
    }
}
// 3. 定义中断回调函数（放在全局变量之后，使用它的函数之前）
void nrf24l01_irq_callback(void *args) {
    uint8_t status = nrf_read_reg(NRF24L01_REG_STATUS);
    LOG_D("IRQ triggered, STATUS=0x%02X", status);

    // 仅处理“接收数据就绪（RX_DR，bit6置1）”
    if (status & (1 << 6)) {
        LOG_D("RX data ready");
        // 读取接收数据到全局缓冲区
        if (nrf24l01_receive_data(g_rx_buffer, PAYLOAD_WIDTH) == RT_EOK) {
            LOG_I("RX data: 0x%02X 0x%02X 0x%02X",
                  g_rx_buffer[0], g_rx_buffer[1], g_rx_buffer[2]);
            g_rx_data_ready = RT_TRUE;  // 置位数据就绪标志
        } else {
            LOG_E("RX data read failed");
        }
        // 清除RX_DR中断标志（写1清除）
        nrf_write_reg(NRF24L01_REG_STATUS, 1 << 6);
    }

    // 忽略发送相关中断（接收模式下无需处理）
    if (status & (1 << 5)) {  // TX_DS（发送完成）
        nrf_write_reg(NRF24L01_REG_STATUS, 1 << 5);
    }
    if (status & (1 << 4)) {  // MAX_RT（最大重发）
        nrf_flush_tx();
        nrf_write_reg(NRF24L01_REG_STATUS, 1 << 4);
    }
}

/* ------------------- 自动初始化 ------------------- */
static int nrf_lcd_init(void) {
    rt_thread_t tid = rt_thread_create(
        "nrf_lcd_test",
        nrf_lcd_test_thread,
        RT_NULL,
        4096,
        RT_THREAD_PRIORITY_MAX / 2,
        20
    );

    if (tid != RT_NULL) {
        rt_thread_startup(tid);
        LOG_I("nRF24L01 LCD test thread created");
    } else {
        LOG_E("Failed to create nRF24L01 LCD test thread");
    }

    return 0;
}
INIT_APP_EXPORT(nrf_lcd_init);
